package com.fzy.hot.ListNode;

public class Test03 {

    /**
     *
     * @param head ListNode类
     * @param k int整型
     * @return ListNode类
     */
    public ListNode reverseKGroup (ListNode head, int k) {
        // write code here

        ListNode dummy = new ListNode(0);
        dummy.next = head;

        ListNode cur = head;
        ListNode pre = dummy;

        while (cur != null){
            ListNode tail = pre;
            for(int i = 0;i<k;i++){
                tail = tail.next;
                if(tail == null){
                    return dummy.next;
                }
            }

            ListNode next = tail.next;
            ListNode[] res = reverse(cur,tail);
            cur = res[0];
            tail = res[1];

            pre.next = cur;
            tail.next = next;
            pre = tail;
            cur = tail.next;
        }

        return dummy.next;
    }
    private ListNode[] reverse(ListNode head,ListNode tail){
        ListNode pre = null;
        ListNode cur = head;
        while (pre != tail){
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return new ListNode[]{tail,head};
    }
}
